import axios from "axios"
import { decrypt } from "@/utils/encryption.js"
import {
  Cookie,
  Toast
} from "../utils"

axios.defaults.withCredentials = true;
axios.defaults.headers["Content-Type"] = "application/json;charset=UTF-8";

const {
  VUE_APP_SKY_API_HOST,
  VUE_APP_LAW_API_HOST,
  VUE_APP_AD_API_HOST,
  VUE_APP_JUMP_URL
} = process.env || {};

/**
 * 后台接口调用
 * @param {*} url 接口地址
 * @param {*} type 请求类型
 * @param {*} params 参数对象
 * @param {*} formSubmit Content-Type类型
 * @param {*} interfaceType law: 法律机器人 ad: 法律审核 sky: 资信核查
 * @returns
 */
async function ajax(url, type, params, formSubmit, interfaceType) {
  const reqObj = {
    host: decrypt(VUE_APP_LAW_API_HOST),
    msg: "系统打盹了，休息一会。", //提示信息
  }

  const headers = {
    aitalk_token: Cookie.getCookie("aitalk_token_fl") || "",
  }

  //判断使用的接口类型，根据不同的类型，域名和token使用的也不一样
  switch (interfaceType) {
    case "sky":
      reqObj.host = decrypt(VUE_APP_SKY_API_HOST);
      //删除对象中的aitalk_token
      Reflect.deleteProperty(headers, "aitalk_token");
      headers["accessToken"] = Cookie.getCookie("accessToken") || "";
      break;
    case "law":
      reqObj.host = decrypt(VUE_APP_LAW_API_HOST);
      break;
    case "ad":
      reqObj.host = decrypt(VUE_APP_AD_API_HOST);
      break;
  }


  if (formSubmit === "formSubmit") {
    headers["Content-Type"] = "multipart/form-data";
  } else if (formSubmit === "form-urlencoded") {
    headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
  }

  try {
    //请求接口数据
    const res = await axios({
      method: type,
      url: reqObj.host + url,
      timeout: 15000,
      headers,
      params: type === "get" ? params : null,
      data: params
    });

    if (res) {
      const {
        data,
        code,
        message,
        result,
        nextLevel,
      } = res.data || {};

      //接口调用成功 接口返回的code或result不同，都需要判断下
      if (code == 200 || code == 1 || result == 1) {
        //nextLevel 判断是企业信息页面的风险详情，需要将nextLevel一起返回，这里单独处理
        if (nextLevel || nextLevel == 0) {
          return {
            data,
            nextLevel
          };
        }
        return data;
      }

      //接口调用出错，如：没有做身份认证
      reqObj.msg = message || reqObj.msg;
      if (reqObj.msg === "token认证失败！") {
        reqObj.msg = "身份认证中...";
        location.replace(decrypt(VUE_APP_JUMP_URL) + "?mx_sso_token=" + localStorage.getItem("mx_sso_token"));
      }
    }
  } catch (error) {
    Toast.fail(error);
  }

  Toast.fail(reqObj.msg);

}

export function get(url, params, interfaceType = "law") {
  return ajax(url, "get", params, "", interfaceType);
}

export function post(url, params) {
  return ajax(url, "post", params);
}

export function formSubmit(url, params, interfaceType = "ad") {
  return ajax(url, 'post', params, "formSubmit", interfaceType);
}

export function formUrlencoded(url, params, interfaceType = "sky") {
  return ajax(url, "post", params, "form-urlencoded", interfaceType);
}
